package service

import (
	"food-mgmt-sys/handler/request"
	"food-mgmt-sys/model"
	"math"

	"github.com/gin-gonic/gin"
)

func Shop(c *gin.Context) {

	var form request.Shop
	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var s model.Shop
	s.ShopUrl = form.ShopUrl
	s.ShopName = form.ShopName
	s.Desc = form.Desc

	if err := s.CreateShop(model.DB); err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func ShopList(c *gin.Context) {

	var form request.ShopList
	// 根据 Content-Type Header 推断使用哪个绑定器。
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	var s model.Shop
	list, err, count := s.ShopList(model.DB, form.PageSize, form.Page)
	if err != nil {
		c.JSON(400, gin.H{
			"code": 400,
			"msg":  "分页失败",
		})
		return
	}

	sum := int(math.Ceil(float64(count) / float64(form.Page)))

	up := form.Page - 1
	if up < 1 {
		up = 1
	}

	down := form.Page - 1
	if down > 1 {
		down = sum
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "分页成功",
		"data": map[string]interface{}{
			"list":      list,
			"page":      form.Page,
			"page_size": form.PageSize,
			"sum":       sum,
			"up":        up,
			"down":      down,
		},
	})
	return

}
